<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
class Custom_Validate_Url extends Zend_Validate_Abstract
{
	const INVALID_URL = 'INVALID_URL';

	private $_checkExist = false;

	protected $_messageTemplates = array(
		self::INVALID_URL => "'%value%' is not a valid URL.",
	);

	function  __construct($checkExist = false) {
		$this->_checkExist = $checkExist;
	}

	public function isValid($value)
	{
		$valueString = (string) $value;
		$this->_setValue($valueString);

		if (!Zend_Uri::check($value)) {
			$this->_error(self::INVALID_URL);
			return false;
		}

		if($this->_checkExist && !$this->_isValidUrl($value))
		{
			$this->_error(self::INVALID_URL);
			return false;
		}

		return true;
	}

	private function _isValidUrl($url)
	{
		$url = @parse_url($url);

		if (!$url)
		{
			return false;
		}

		$url = array_map('trim', $url);
		$url['port'] = (!isset($url['port'])) ? 80 : (int)$url['port'];
		$path = (isset($url['path'])) ? $url['path'] : '';

		if ($path == '')
		{
			$path = '/';
		}

		$path .= (isset($url['query'])) ? "?$url[query]" : '';

		if (isset($url['host']) AND $url['host'] != gethostbyname($url['host']))
		{
			if (PHP_VERSION >= 5)
			{
				$headers = get_headers("$url[scheme]://$url[host]:$url[port]$path");
			}
			else
			{
				$fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 30);

				if (!$fp)
				{
					return false;
				}
				fputs($fp, "HEAD $path HTTP/1.1\r\nHost: $url[host]\r\n\r\n");
				$headers = fread($fp, 4096);
				fclose($fp);
			}
			$headers = (is_array($headers)) ? implode("\n", $headers) : $headers;
			return (bool)preg_match('#^HTTP/.*\s+[(200|301|302)]+\s#i', $headers);
		}
		return false;
	}
}
?>
